package org.coderjonny.log;


import com.alibaba.fastjson2.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.coderjonny.dto.Result;
import org.coderjonny.exception.BusinessException;
import org.coderjonny.thread.ThreadLocalUtil;
import org.coderjonny.trace.TraceIdUtil;
import org.slf4j.Logger;
import org.slf4j.MDC;

import java.util.Objects;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class LogEntity {
    // 应用 类 方法 是否成功 异常类型 入参 出参  耗时 异常（有就append）
    private static final String LOG_FORMAT = "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%sms\t%s\r\n";
    private Object request;
    private Object response;
    private Long time = System.currentTimeMillis();
    private String clazz;
    private String method;
    private Throwable throwable;
    private String traceId;
    private String application;


    public void log(Logger logger){
        try{
            // 0 成功    1 失败
            int status = 0;
            // 0 无异常 1 系统异常  2 业务异常
            int errorType = 0;
            if(throwable != null){
                status = 1;
                if (throwable instanceof BusinessException){
                    errorType = 2;
                }else{
                    errorType = 1;
                }
            }
            String log = String.format(LOG_FORMAT,application,clazz,method,status,errorType, JSONObject.toJSONString(request),
                    JSONObject.toJSONString(response),time,traceId);
            if (throwable == null){
                logger.info(log);
            }else{
                logger.error(log,throwable);
            }
        }finally {
            MDC.remove(TraceIdUtil.SLEUTH_TRACE_NAME);
        }
    }
}
